﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Ked
{
    class QueueItem
    {
        public object mParam;

        public Action<object> mAction;
    }
    class StatusThreadPool
    {
        private List<Thread> mThreadList = new List<Thread>();

        private volatile List<QueueItem> mQueueList = new List<QueueItem>();

        private int mExpectedThreadCount;

        public StatusThreadPool(int length)
        {
            mExpectedThreadCount = length;
        }

        private void initThreads()
        {
            while (true)
            {

            }
            
        }

        private volatile int mCounter;

        private void AddThread()
        {
            lock (this)
            {
                Thread thread = new Thread(DoQueue);
                thread.Name = mCounter.ToString();
                thread.Start();
                mThreadList.Add(thread);
                mCounter++;
            }
        }

        private volatile bool mExitable = false;

        private void DoQueue()
        {
            while (true)
            {
                QueueItem item = null;
                lock (this)
                {
                    item = mQueueList.Last();
                }
                if(item==null
                    && mExitable)
                {
                    mExitable = false;
                    break;
                }
                //执行动作
                item.mAction?.Invoke(item.mParam);
            }
            OnThreadExit();
        }

        private void OnThreadExit()
        {
            Thread current = Thread.CurrentThread;
            Debug.Print("thread:" + current.Name + " is exitable");
            lock (this)
            {
                mThreadList.Remove(current);
                mCounter--;
                while (mCounter < mExpectedThreadCount)
                {
                    if(mQueueList.Count>0)
                        AddThread();
                }
                if (mCounter <= 0)
                {
                    Debug.Print("should teminate thread pool");
                    OnAllFinished?.Invoke(this, null);
                }
            }

        }

        public event EventHandler OnAllFinished;


    }
}
